/**
 * @author guocailee
 * @description require vue-resource
 */
import VueProgressBar from 'vue-progressbar'
import message from '../config/message'
import resource from '../config/resource'
import * as loginInfoUtil from './loginInfo.js'

let mergeParams = (params) => {
  loginInfoUtil.setExpired()
  let loginInfo = loginInfoUtil.getInfo() || {}
  let copyMessage = JSON.parse(JSON.stringify(message))
  copyMessage.sessionId = loginInfo.sessionId
  copyMessage.payload.params = params || {}
  return copyMessage
}
let $fetch = (Vue) => {
  let fetch = {};
  ['get', 'delete', 'head', 'jsonp'].forEach((method) => {
    fetch[method] = function (url, options) {
      return new Promise((resolve, reject) => {
        // Vue.$Progress.start()
        Vue.http[method](url, options).then((data) => {
          // Vue.$Progress.finish()
          resolve(data)
        }).catch(data => {
          // Vue.$Progress.fail()
          reject(data)
        })
      })
    }
  });

  ['post', 'put', 'patch'].forEach((method) => {
    fetch[method] = function (url, body, options) {
      return new Promise((resolve, reject) => {
        // Vue.$Progress.start()
        Vue.http[method](url, mergeParams(body), options).then((data) => {
          // Vue.$Progress.finish()
          resolve(data)
        }).catch(data => {
          // Vue.$Progress.fail()
          reject(data)
        })
      })
    }
  })
  return fetch
}
let plugin = (Vue) => {
  if (plugin.installed) {
    return
  }
  Vue.use(VueProgressBar, {
    color: 'rgb(143, 255, 199)',
    failedColor: 'red',
    height: '2px'
  })
  if (!Vue.http) {
    if (console && console.warn) {
      console.warn('Fetch util require vue-resource, You should use vue-resource before use Fetch Util')
    }
    return
  }
  Vue.http.options.root = resource.root
  Vue.fetch = $fetch(Vue)
  Vue.prototype.$fetch = Vue.fetch
}
export default plugin
